package net.thxjj.netty;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import net.model.device.BaseBean;
import net.model.device.DeviceBean;
import net.model.device.LoginBean;
import net.model.device.ProductBean;
import net.model.deviceresp.DevRespBean;
import net.model.deviceresp.DevRespParams;
import net.thxjj.error.ActionType;
import net.thxjj.error.BizException;
import net.thxjj.error.ErrCode;
import net.thxjj.error.LoginErrorListener;
import net.thxjj.standard.NewTernary;
import net.thxjj.standard.TernaryCodeUtil;
import net.util.ParameterMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import java.util.logging.Logger;

@Component
public class DevLoginHandler extends HeartBeatBaseChannelInBoundHandler {
    private Logger log = Logger.getLogger(String.valueOf(this.getClass()));
    private LoginErrorListener loginErrorListener;



    public DevLoginHandler() {
    }



    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, BaseBean s) throws Exception {

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx,msg);
        if(!DeviceSocketMap.hasDevice(ctx.channel())){


                String de = (String)msg;
                LoginBean loginBean =  JSONObject.parseObject(de, LoginBean.class);
                log.info(loginBean.toString());
                //params字段缺失报错
                if(loginBean.getParams()==null){
                    DevRespBean devRespBean =  new DevRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.PARAMS_IS_NOT_EXIST_ERROR.getCode(),ErrCode.PARAMS_IS_NOT_EXIST_ERROR.getDescription(),null);
                    ctx.writeAndFlush(devRespBean.toString());
                    ctx.close();
                    return;
                }

                String devTid = loginBean.getParams().getDevTid();
                //devTid字段缺失报错
                if(StringUtils.isEmpty(devTid)){
                    DevRespBean devRespBean =  new DevRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.DEVTID_EMPTY_ERROR.getCode(),ErrCode.DEVTID_EMPTY_ERROR.getDescription(),null);
                    ctx.writeAndFlush(devRespBean.toString());
                    ctx.close();
                    return;
                }


                String prodkey = loginBean.getParams().getProdKey();
                //prodkey字段缺失报错
                if(StringUtils.isEmpty(prodkey)){
                    DevRespBean devRespBean =  new DevRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.PROPERTY_NOT_EXIST_ERROR.getCode(),ErrCode.PROPERTY_NOT_EXIST_ERROR.getDescription(),null);
                    ctx.writeAndFlush(devRespBean.toString());
                    ctx.close();
                    return;
                }

             //校验prodkey是否存在
            ProductBean productBean = productService.getProductBean(prodkey);
                if(productBean == null){
                    DevRespBean devRespBean =  new DevRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.PRODUCTKEY_NOT_EXIST_ERROR.getCode(),ErrCode.PRODUCTKEY_NOT_EXIST_ERROR.getDescription(),null);
                    ctx.writeAndFlush(devRespBean.toString());
                    ctx.close();
                    return;
                }

            ParameterMap parameterMap = new ParameterMap();
            parameterMap.put("device_id",devTid);
            parameterMap.put("prod_key",prodkey);
             DeviceBean deviceBean = deviceService.getDevice(parameterMap);
                String token = loginBean.getParams().getToken();
                if(StringUtils.isEmpty(token)){
                    //新设备第一次上线成功
                    DevRespParams params = new DevRespParams();
                    params.setDevTid(devTid);
                    params.setProdKey(prodkey);
                    if(deviceBean == null){
                        //新设备第一次上线成功
                        NewTernary newTernary = TernaryCodeUtil.CreateDeviceTernary(devTid,prodkey);
                        params.setBindKey(newTernary.getNewBindkey());
                        params.setCtrlKey(newTernary.getNewCtrlkey());
                        params.setToken(newTernary.getNewToken());
                        //持久化生成新的设备
                        ParameterMap parameterMap1 = new ParameterMap();
                        parameterMap1.put("device_id",devTid);
                        parameterMap1.put("token",newTernary.getNewToken());
                        parameterMap1.put("bind_key",newTernary.getNewBindkey());
                        parameterMap1.put("ctrl_key",newTernary.getNewCtrlkey());
                        parameterMap1.put("create_time",System.currentTimeMillis());
                        parameterMap1.put("prod_key",prodkey);
                        parameterMap1.put("net_status",1);
                        parameterMap1.put("remote_ip",ctx.channel().remoteAddress().toString());
                        parameterMap1.put("login_time",System.currentTimeMillis());
                        parameterMap1.put("online_at",System.currentTimeMillis());
                        parameterMap1.put("login_ip",ctx.channel().remoteAddress().toString());
                        deviceService.insertDevNewInfo(parameterMap1);
                    } else {
                        params.setBindKey(deviceBean.getBindKey());
                        params.setCtrlKey(deviceBean.getCtrlKey());
                        params.setToken(deviceBean.getToken());

                        ParameterMap parameterMap1 = new ParameterMap();
                        parameterMap1.put("device_id",devTid);
                        parameterMap1.put("net_status",1);
                        deviceService.updateDevOnlineStatus(parameterMap1);
                    }
                    DevRespBean devRespBean =  new DevRespBean(loginBean.getMsgId(), ActionType.DEVICE_LOGINRESP.getName(), ErrCode.SUCCESS.getCode(),ErrCode.SUCCESS.getDescription(),params);
                    ctx.writeAndFlush(devRespBean.toString());
                    //上线一个设备
                    DeviceSocketMap.addDevice(ctx.channel(),devTid,prodkey);

                }else {

                    //不存在此设备
                    if(deviceBean == null){
                        DevRespBean devRespBean =  new DevRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.DEVICE_NOT_EXIST_ERROR.getCode(),ErrCode.DEVICE_NOT_EXIST_ERROR.getDescription(),null);
                        ctx.writeAndFlush(devRespBean.toString());
                        ctx.close();
                    }else{
                        ParameterMap map = new ParameterMap();
                        map.put("device_id",devTid);
                        DeviceBean deviceBeanSnap = deviceService.getDevice(map);
                        //校验token
                        if(!token.equals(deviceBeanSnap.getToken())){
                            DevRespBean devRespBean =  new DevRespBean(loginBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.DEVICE_TOKEN_ERROR.getCode(),ErrCode.DEVICE_TOKEN_ERROR.getDescription(),null);
                            ctx.writeAndFlush(devRespBean.toString());
                            ctx.close();
                        }else{

                            ParameterMap parameterMap1 = new ParameterMap();
                            parameterMap1.put("device_id",devTid);
                            parameterMap1.put("net_status",1);
                            deviceService.updateDevOnlineStatus(parameterMap1);

                            DevRespParams params = new DevRespParams();
                            params.setDevTid(devTid);
                            params.setBindKey(deviceBean.getBindKey());
                            params.setCtrlKey(deviceBean.getCtrlKey());
                            params.setToken(token);
                            params.setProdKey(prodkey);
                            DevRespBean devRespBean =  new DevRespBean(loginBean.getMsgId(), ActionType.DEVICE_LOGINRESP.getName(), ErrCode.SUCCESS.getCode(),ErrCode.SUCCESS.getDescription(),params);
                            ctx.writeAndFlush(devRespBean.toString());
                            //上线一个设备
                            DeviceSocketMap.addDevice(ctx.channel(),devTid,prodkey);
                        }

                    }


                }



        }else{
            ctx.close();
            throw  new BizException("恶意连接");
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }



}
